package com.example.common.utils;

import com.example.common.exception.ExceptionCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class ValidateUtils {

    /**
     * 获取JSR303校验失败错误信息
     * @param bindingResult
     * @return
     */
    public static Map<String,String> getValidationErrMsg(BindingResult bindingResult) {
        Map<String,String> err = new HashMap<>();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        fieldErrors.stream().forEach(item -> {
            // 获取错误字段的名称
            String fieldName = item.getField();
            // 获取错误信息
            String errMsg = item.getDefaultMessage();
            // 封装所有错误信息到map中
            err.put(fieldName,errMsg);
        });
        return err;
    }

    public static R handleValidException(MethodArgumentNotValidException e) {
        Map<String, String> errMsg = getValidationErrMsg(e.getBindingResult());
        log.error("参数校验异常：============== {}",errMsg);
        return R.error(ExceptionCodeEnum.PARAM_VALIDATE_EXCEPTION.getCode(),ExceptionCodeEnum.PARAM_VALIDATE_EXCEPTION.getMessage()).put("data",errMsg);
    }

    public static R handleBindException(BindException e) {
        Map<String, String> errMsg = getValidationErrMsg(e.getBindingResult());
        log.error("参数校验异常：============== {}",errMsg);
        return R.error(ExceptionCodeEnum.PARAM_VALIDATE_EXCEPTION.getCode(),ExceptionCodeEnum.PARAM_VALIDATE_EXCEPTION.getMessage()).put("data",errMsg);
    }
}
